<?php


namespace App\Excel\Export;


use App\Http\Search\Order\ListIndexSearch;
use App\Models\OrderProduct;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class OrderExport extends DefaultValueBinder implements FromQuery, WithHeadings, WithMapping, WithCustomValueBinder
{
    use Exportable;

    /**
     * @var ListIndexSearch
     * @author luffyzhao@vip.126.com
     */
    protected $search;

    /**
     * ProductExport constructor.
     * @param ListIndexSearch $search
     */
    public function __construct(ListIndexSearch $search)
    {
        $this->search = $search;
    }


    /**
     * @return Builder
     */
    public function query()
    {
        return OrderProduct::query()->with('order')->whereIn('order_id', function (Builder $query){
            $query->from('orders')->select(['id'])->where($this->search->toArray());
        });
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return ['订单号', '订购人姓名', '订购人手机号', '订购人身份证', '收件人', '收件人手机号', '收件人地址', '省', '市', '区', '商品货值', '商品税费', '商品优惠券', '商品运费', '实际支付','说明', '商品SKU', '商品数量', '商品单价',];
    }

    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($row): array
    {
        return [
            $row->order->order_code,
            $row->order->buyer_name,
            $row->order->buyer_phone,
            $row->order->buyer_id_number,
            $row->order->receiving_name,
            $row->order->receiving_phone,
            $row->order->receiving_address,
            $row->order->receiving_province,
            $row->order->receiving_city,
            $row->order->receiving_district,
            $row->order->goods_value,
            $row->order->tax,
            $row->order->discount,
            $row->order->freight,
            $row->order->payment,
            $row->order->remark,
            $row->sku,
            $row->quantity,
            $row->price,
        ];
    }



    /**
     * @param Cell $cell
     * @param mixed $value
     * @return bool
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @author luffyzhao@vip.126.com
     */
    public function bindValue(Cell $cell, $value)
    {
        if(in_array($cell->getColumn(), ['A','C','D','F','P'])){
            $cell->setValueExplicit($value, DataType::TYPE_STRING);
            return true;
        }
        return parent::bindValue($cell, $value);
    }
}
